﻿using BootstrapAdmin.DataAccess.Models;
using BootstrapAdmin.Web.Core.Services.Production;
using PetaPoco;

namespace BootstrapAdmin.DataAccess.PetaPoco.Services.Production;

/// <summary>
/// 存档信息服务
/// </summary>
internal sealed class ArchiveInfoService : IArchiveInfoService
{
    private readonly IDBManager _dbManager;

    public ArchiveInfoService(IDBManager db) => _dbManager = db;

    public async Task<(List<Archive> items, int count)> GetPagedAsync(ArchiveInfoFilter filter, int pageIndex, int pageItems)
    {
        var sql = new Sql();
        if (!string.IsNullOrEmpty(filter.Station))
        {
            sql.Where("Station = @0", filter.Station);
        }

        if (!string.IsNullOrEmpty(filter.SN))
        {
            sql.Where("SN = @0", filter.SN);
        }

        if (filter.CreatedTimeStart != null)
        {
            sql.Where("CreatedAt >= @0", filter.CreatedTimeStart);
        }

        if (filter.CreatedTimeEnd != null)
        {
            sql.Where("CreatedAt <= @0", filter.CreatedTimeEnd);
        }

        sql.OrderBy("CreatedAt");

        using var db = _dbManager.Create();
        var data = await db.PageAsync<Archive>(pageIndex, pageItems, sql);
        return (data.Items, Convert.ToInt32(data.TotalItems));
    }

    public List<ArchiveItem> GetArchiveItems(int archiveId)
    {
        var sql = new Sql();
        sql.Where("ArchiveId = @0", archiveId);
        using var db = _dbManager.Create();

        var items = db.Fetch<ArchiveItem>(sql);
        return items;
    }
}
